import { Query } from '@/hook/mapgis-api/Query'
import { ref, nextTick } from 'vue'
import { useCommonStore } from '@/stores/common'
import { storeToRefs } from 'pinia'

/** 图层服务 */
let service = {
  name: import.meta.env.VITE_DOC_NAME,
  /* 图层id */
  layerId: 2
}

Query.queryByLayerId({
  service,
  success: (feature) => {
    // console.log(feature)
    AxisPrepare(feature)
  }
})
/**饼图数据 */
let pieData = []
let PieChart = {}
/**折线图数据 */
let LineData = []
let LineChartYear = {}
/**折线图月数据 */
let LineDataMonth = []
let LineChartMonth = {}

/**轴值处理函数 */
const AxisPrepare = (data) => {
  const prepare = []
  data.forEach((item) => {
    prepare.push({
      xTime: item.get('values_').发生时间.split('.')[0],
      xTimeMonth: parseInt(item.get('values_').发生时间.split('.')[1]),
      yValue: item.get('values_').事件类型
    })
  })
  /**饼图数据获取函数 */
  pieData = prepare.reduce((accumulator, currentItem) => {
    // 检查当前yValue是否已经在accumulator中
    const existingCount = accumulator.find((item) => item.name === currentItem.yValue)
    if (existingCount) {
      // 如果存在，则增加计数
      existingCount.value++
    } else {
      // 如果不存在，则添加新的yValue和计数
      accumulator.push({ name: currentItem.yValue, value: 1 })
    }
    return accumulator
  }, []) // 初始值是一个空数组

  // 获取唯一的年份
  const uniqueYears = [...new Set(prepare.map((item) => item.xTime))]
  // 计算年份出现的次数（即数组的长度）
  const yearCount = uniqueYears.map((year) => prepare.filter((item) => item.xTime === year).length)
  // LineData = [uniqueYears, yearCount]
  let combinedData = uniqueYears.map((year, index) => {
    return { year: year, count: yearCount[index] }
  })
  // 按年份大小排序
  combinedData.sort((a, b) => a.year - b.year)
  // 重新分离成 uniqueYears 和 yearCount
  const sortedUniqueYears = combinedData.map((item) => item.year)
  const sortedYearCount = combinedData.map((item) => item.count)
  //构造 LineData
  LineData = [sortedUniqueYears, sortedYearCount]
  // console.log(LineData)
  //   console.log(LineData, pieData)
  // 设定月份
  const uniqueMonths = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
  // 计算年份出现的次数（即数组的长度）
  const monthCount = uniqueMonths.map(
    (month) => prepare.filter((item) => item.xTimeMonth === month).length
  )
  LineDataMonth = [uniqueMonths, monthCount]
}

/**渲染图表 */
const renderChart = () => {
//   /* 引入公共状态管理对象 */
//   const store = useCommonStore()
//   const { allChartFlag } = storeToRefs(store)
  LineChartYear = {
    title: {
      text: '事故统计图'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    xAxis: {
      type: 'category',
      data: LineData[0],
      axisLabel: {
        formatter: '{value}年'
      }
    },
    yAxis: {},
    series: [
      {
        name: '事故数量',
        type: 'line',
        data: LineData[1],
        formatter: '{c}'
      }
    ],
    toolbox: {
      show: true,
      feature: {
        mark: { show: true },
        dataView: { show: true, readOnly: false },
        magicType: { show: true, type: ['pie', 'funnel'] },
        restore: { show: true },
        saveAsImage: { show: true }
      }
    }
  }
  LineChartMonth = {
    title: {
      text: '事故统计图'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}月 : {c}起'
    },
    xAxis: {
      type: 'category',
      data: LineDataMonth[0],
      axisLabel: {
        formatter: '{value}月'
      }
    },
    yAxis: {},
    series: [
      {
        name: '事故数量',
        type: 'line',
        data: LineDataMonth[1],
        label: {
          show: true,
          formatter: function (params) {
            return params.value + '起'
          }
        }
      }
    ],
    toolbox: {
      show: true,
      feature: {
        mark: { show: true },
        dataView: { show: true, readOnly: false },
        magicType: { show: true, type: ['pie', 'funnel'] },
        restore: { show: true },
        saveAsImage: { show: true }
      }
    }
  }
  PieChart = {
    title: {
      text: '事故类型统计图'
    },
    legend: {
      right: '20px',
      bottom: '20px',
      orient: 'vertical',
      data: pieData.map((item) => item.name)
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    series: [
      {
        name: '事故类型',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '50%'],
        // roseType: 'area',
        itemStyle: {
          borderRadius: 10
        },
        data: pieData
      }
    ],
    toolbox: {
      show: true,
      feature: {
        mark: { show: true },
        dataView: { show: true, readOnly: false },
        magicType: { show: true, type: ['pie', 'funnel'] },
        restore: { show: true },
        saveAsImage: { show: true }
      }
    }
  }
//   allChartFlag.value = true
}

export { renderChart, LineChartMonth, LineChartYear, PieChart }
